#include "Lsqlite.h"


Lsqlite::Lsqlite(){m_sql = NULL;}

Lsqlite::~Lsqlite()
{
	Close();
}

int Lsqlite::Open()
{
	if(m_sql)
		return 0;

	return sqlite3_open(PAOMA_SQLITE_FILE,&m_sql);
}

int Lsqlite::Close()
{
	int code = 0;
	if(m_sql)
	{
		code = sqlite3_close(m_sql);

		if(code == SQLITE_OK)
			m_sql = NULL;
	}
	return code;
}

int Lsqlite::DoCommand(char* cmd)
{
	sqlite3_stmt* stmt = NULL;
	int r = sqlite3_prepare_v2(m_sql,cmd,(int)strlen(cmd),&stmt,NULL);
	if( SQLITE_OK == r)
		r = sqlite3_step(stmt);

	sqlite3_finalize(stmt);
	return r;
}


int Lsqlite::CreateTable()
{
	Open();

	char cmd[1024]={0};
	sprintf(cmd,CREATE_PAOMA_TABLE);
	return DoCommand(cmd);

}

int Lsqlite::DeleteTable()
{
	Open();

	char cmd[1024]={0};
	sprintf(cmd,DELETE_PAOMA_TABLE);
	return DoCommand(cmd);
}


int Lsqlite::Insert(int first,int second,int mul,int index,char* date)
{
	Open();

	char cmd[1024]={0};
	sprintf(cmd,INSERT_PAOMA_TABLE,first,second,mul,index,date);
	return DoCommand(cmd);
}

int Lsqlite::Insert(PaoMaMSG& msg)
{
	return Insert(msg.first,msg.second,msg.mul,msg.index,msg.date);
}

int Lsqlite::Query(PM_CALLBACK callfunc,void* opt)
{
	Open();

	char cmd[1024]={0};
	sprintf(cmd,SELECT_PAOMA_TABLE);

	sqlite3_stmt* stmt = NULL;
	int r = sqlite3_prepare_v2(m_sql,cmd,(int)strlen(cmd),&stmt,NULL);
	if( SQLITE_OK != r)
	{
		sqlite3_finalize(stmt);
		return r;
	}

	int len = sqlite3_column_count(stmt);
	
	r = sqlite3_step(stmt);
	while(r == SQLITE_ROW && len == 5)
	{
		PaoMaMSG msg;
		memset(&msg,0,sizeof(msg));
		int* p = (int*)&msg;
		for(int i = 0 ;i < 4 ; i++)
		{
			p[i] = sqlite3_column_int(stmt,i);
		}
		const unsigned char* date = sqlite3_column_text(stmt,4);
		memcpy(&msg.date,date,strlen((const char*)date));

		callfunc(msg,opt);
		r = sqlite3_step(stmt);
	}
	sqlite3_finalize(stmt);

	return r == SQLITE_DONE ? 0 : -1;
}

